import Api from '../request/api.js';
import { log, md5, sleep } from '../utils/utils.js';
import Leying from '../lib/Leying.js';
import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
puppeteer.use(StealthPlugin());
const pgs = new Leying();
const API = new Api();
const {
  CINEMA_NAME,
  CINEMA_ACCOUNT,
  CINEMA_FORCE_COUPON,
  CINEMA_COUPON_FEE,
  CINEMA_COUPON_NUM,
  CINEMA_VIP_BALANCE,
} = process.env;
const clientTimeout = 5;

// const data = [
//   {
//     id: 279,
//     sn: 'SO_202343194731176125106',
//     sellAmount: '0.00',
//     sectionId: '01',
//     screenshot: true,
//     filmName: '超级马力欧兄弟大电影',
//     showTimestamp: 1681870500000,
//     cinemaName: '九州中原全激光影城(外高桥森兰商都DTS：X店)',
//     accountId: 18,
//     showDate: '05-08',
//     showTime: '10:15',
//     seatList: ['12排13座', '12排14座'],
//   },
// ];

// 乐影出票控制器
export default async function LeyingTicketClient() {
  log(
    `乐影初始化完成\n${CINEMA_NAME}\n券成本:${CINEMA_COUPON_FEE}\n剩余券数:${CINEMA_COUPON_NUM}\n余额:${CINEMA_VIP_BALANCE}\n出票方式:${CINEMA_FORCE_COUPON}\n+++++++\n`
  );

  let updtime = Date.now();
  let dataJson = null;
  while (true) {
    try {
      // 获取一条记录
      dataJson = await API.getOneRecord();
      //   dataJson = data.pop();
      const now = Date.now();
      if (!dataJson) {
        if (updtime < now - clientTimeout * 1000) {
          // 退出子程序
          process.exit(0);
        }
        await sleep(4000);
        continue;
      }
      updtime = now;
      log('开始出票 ' + JSON.stringify(dataJson));
      await pgs.orderStart(dataJson);

      // 判断是否已经出票
      let orderInfo = await pgs.getOrderInfo();
      if (orderInfo) {
        await API.ticket({
          id: dataJson.id,
          payType: orderInfo.payType,
          msg: '出票成功(文件)',
          ticketContent: orderInfo.ticketCode,
          status: 1,
          sceenshot: orderInfo.uploadLink || '',
          settleAmount: 0, // 真实成本
        });
        log(`出票成功(文件) ${orderInfo.ticketCode} +++++++ \n\n`);
        continue;
      }

      // 获取影院信息
      const cinemaInfo = await API.cinemaInfo(dataJson.id);

      //   console.log(JSON.stringify(cinemaInfo));

      // 获取座位
      await pgs.getSeat();

      // 选座
      await pgs.lockSeat();

      // 提交订单信息返回出票信息
      orderInfo = await pgs.submitOrderInfo(cinemaInfo);
      if (orderInfo) {
        log(`出票成功 ${orderInfo.ticketCode} +++++++ \n\n`);
        await API.ticket({
          id: dataJson.id,
          payType: orderInfo.payType,
          msg: '出票成功',
          ticketContent: orderInfo.ticketCode,
          status: 1,
          sceenshot: orderInfo.uploadLink || '',
          settleAmount: 0, // 真实成本
        });
      } else {
        log('出票失败 +++++++++++++\n\n', 'error');
        await API.ticket({
          id: dataJson.id,
          msg: '出票失败',
          ticketContent: '',
          payType: 0,
          status: 2,
          settleAmount: 0, // 真实成本
        });
      }
    } catch (error) {
      log(`出票异常[${CINEMA_ACCOUNT}] ` + error.stack, 'error');
      console.error(error);

      // 订单回退
      if (dataJson) {
        dataJson.msg = `${error.message}[${CINEMA_ACCOUNT}]`;
        await pgs.orderRollback(dataJson);
      }
    }

    dataJson = null;
  }
}
